<template>
    <el-dialog :title="title" v-model="visible" width="800px" :before-close="cancel" append-to-body>
       <el-form ref="roleRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
             <el-input v-model="form.roleName" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item prop="roleKey">
             <template #label>
                <span>
                   <el-tooltip content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasRole('admin')`)" placement="top">
                      <el-icon><question-filled /></el-icon>
                   </el-tooltip>
                   权限字符
                </span>
             </template>
             <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
          </el-form-item>
          <el-form-item label="角色顺序" prop="roleSort">
             <el-input-number v-model="form.roleSort" controls-position="right" :min="0" />
          </el-form-item>
          <el-form-item label="状态">
             <el-radio-group v-model="form.roleStatus">
                <el-radio
                   v-for="dict in sys_normal_disable"
                   :key="dict.value"
                   :label="dict.value"
                >{{ dict.label }}</el-radio>
             </el-radio-group>
          </el-form-item>
          <el-form-item label="菜单权限">
             <!-- <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
             <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选</el-checkbox> -->
             <!-- <el-checkbox v-model="menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动</el-checkbox> -->
             <el-tree
                class="tree-border"
                :data="props.menuOptions"
                show-checkbox
                ref="menuRef"
                node-key="perms"
                :check-strictly="menuCheckStrictly"
				:default-checked-keys="perms"
                empty-text="加载中，请稍候"
                :props="{ label: 'menu_name', children: 'children' }"
             ></el-tree>
          </el-form-item>
          <el-form-item label="备注">
             <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
          </el-form-item>
       </el-form>
       <template #footer>
          <div class="dialog-footer">
             <el-button type="primary" @click="submitForm">确 定</el-button>
             <el-button @click="cancel">取 消</el-button>
          </div>
       </template>
    </el-dialog>
</template>

<script setup>
import { addRole, updateRole } from "@/api/system/role";
const { proxy } = getCurrentInstance();
const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
// import { roleMenuTreeselect, treeselect as menuTreeselect } from "@/api/system/menu";

const props = defineProps({
  title: {
  	default: "",
  	type: String
  },
  visible: {
  	default: false,
  	type: Boolean
  },
  info: {
	default: () => {},
	type: Object
  },
  menuOptions: {
	  default: () => [],
	  type: Array
  }
});

 const visible = computed({
   get: () => props.visible,
   set: (val) => {
     emit('update:visible', val);
   }
 });
 
const emigFun = defineEmits(["click"]);

const menuRef = ref(null);
const menuExpand = ref(false);
const menuNodeAll = ref(false);
const menuCheckStrictly = ref(false);
const checkNodeKey = ref('')

const data = reactive({
  form: {
	  id: undefined,
	  roleName: '',
	  roleKey: '',
	  roleSort: 0,
	  roleStatus: "0",
	  perms: '',
	  remark: ''
  },
  perms: [],
  rules: {
    roleName: [{ required: true, message: "角色名称不能为空", trigger: "blur" }],
    roleKey: [{ required: true, message: "权限字符不能为空", trigger: "blur" }],
    roleSort: [{ required: true, message: "角色顺序不能为空", trigger: "blur" }]
  },
});

const { form, rules, perms } = toRefs(data);

function getInfo() {
	console.log(props.info)
	if (props.info) {
		form.value = props.info
		perms.value = props.info.perms
	}
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
  menuTreeselect().then(response => {
    menuOptions.value = response.data;
  });
}

/** 所有菜单节点数据 */
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menuRef.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menuRef.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

// 父子联动
const handleCheckedTreeConnect = (e, name) => {
	menuCheckStrictly.value = e ? false : true;
	console.log(e, menuCheckStrictly.value)
}

/** 提交按钮 */
function submitForm() {
	// 目前被选中的菜单节点
	let checkedKeys = proxy.$refs['menuRef'].getCheckedKeys();
	// 半选中的菜单节点
	let halfCheckedKeys = proxy.$refs['menuRef'].getHalfCheckedKeys();
	// 全部节点
	let allCheckedKeys = [...checkedKeys, ...halfCheckedKeys].filter(item => item !== '');
  proxy.$refs["roleRef"].validate(valid => {
	if (valid) {
	  if (form.value.id != undefined) {
		form.value.perms = allCheckedKeys
		updateRole(form.value).then(response => {
		  proxy.$modal.msgSuccess("修改成功");
		  cancel();
		});
	  } else {
		// form.value.menuIds = getMenuAllCheckedKeys();
		addRole(form.value).then(response => {
		  proxy.$modal.msgSuccess("新增成功");
		  cancel();
		});
	  }
	}
  });
}

/** 取消按钮 */
function cancel() {
  emigFun('click', false)
}

getInfo()
// getMenuTreeselect()

</script>
